package com.feng.fengmall.auth2.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.feng.fengmall.auth2.feign.MemberFeignService;
import com.feng.fengmall.auth2.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class RegController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/reg.html")
    public String regPage(){
        return "reg";
    }

    /**
     *
     *   //TODO 重定向携带数据，利用session原理。将数据放在session中。
     *     只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉
     *
     *  //TODO 1、分布式下的session问题。
     * RedirectAttributes redirectAttributes：模拟重定向携带数据
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes,
                         HttpSession session){
        System.out.println("========================");
        System.out.println(vo);
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:20000/reg.html";
        }
        R r = memberFeignService.regist(vo);
        if(r.getCode() == 0){
            //成功
            return "redirect:http://localhost:20000/login.html";
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:20000/reg.html";
        }
    }
}
